﻿using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Mvc;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Op.Common;
using YouWei.Op.Models.Sms;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace YouWei.Op.Controllers
{
    public class SmsController : BaseController
    {
        SmsCardService cardService = new SmsCardService();
        SmsTaskService taskService = new SmsTaskService();
        SmsTaskTimeService timeService = new SmsTaskTimeService();
        SmsBlackDayService ldayService = new SmsBlackDayService();
        SmsTemplateService templateService = new SmsTemplateService();
        SmsTaskTimeStatsticsService statsticService = new SmsTaskTimeStatsticsService();

        SmsMessagePoolService svMessagePool=new SmsMessagePoolService();

      

        #region 短信卡池管理
        [AllowAnonymous]
        public ActionResult CarList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult SmsCardList(ReqSmsCardCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<SmsCardDto> page = cardService.GetPages(pageIndex, pageSize, model);
            return ReturnResult(page);
        }

        public ActionResult CardEdit()
        {
            SmsCard info = new SmsCard();
            int id = Utility.EConvert.ToInt(GetParam("carid"), 0);
            if (id > 0)
            {
                info = cardService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存卡片信息
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveCard(ReqCard reqModel)
        {
            var res = new ResultData<string>();
            SmsCard info = null;
            if (cardService.CheckMobile(reqModel.txtOwnerMobile, reqModel.CardId))
            {
                res.message = "手机号已经存在";
                res.status = -1;
                return ReturnResult(res);
            }
            if (reqModel.CardId > 0)
            {
                info = cardService.Single(reqModel.CardId);
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
            }
            else
            {
                info = new SmsCard();
                info.CreatedTime = DateTime.Now;
                info.CreatedUserID = CurrentUser.UserId;
             
            }

            info.OwnerName = reqModel.txtOwnerName;
            info.OwnerMobile = reqModel.txtOwnerMobile;
            info.PortNumber = reqModel.txtPortNumber;
            info.TelType = reqModel.selTelType;
            info.CountPerHour = reqModel.txtCountPerHour;
            info.CountPerDay = reqModel.txtCountPerDay;
            try
            {
                if (info.CardID <= 0)
                {
                    cardService.Insert(info);
                }
                else
                {
                    cardService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        //public ContentResult ReplaceCard()
        //{
        //    ResultData<bool> rData = new ResultData<bool>();
        //    try
        //    {
        //        var listCurrentPorts = svPort.GetCurrentRunPorts();
        //        //先禁用所有卡片，再更新目前正在运行的卡片状态
        //        cardService.DisabledAllSmsCards();
        //        foreach (var port in listCurrentPorts)
        //        {
        //            cardService.SafeInsertCard(port.PhoNum);
        //        }

        //        rData.status = 0;
        //        rData.data = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        Log4netLog.Error("换卡时出错了！！"+ex.ToString());
        //        rData.status = -1;
        //        rData.message = "操作失败，message："+ex.Message;
        //    }
           
        //    return ReturnResult(rData);
        //}

        /// <summary>
        /// 删除卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelCard(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            SmsCard info = cardService.Single(id);
            if (info != null)
            {
                info.IsDeleted = 1;
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
                cardService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 启用卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult EnableCardByIds(List<int> ids)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (ids.Count == 0)
            {
                rData.status = -1;
                rData.message = "没有要启动的短信卡";
                return ReturnResult(rData);
            }

            if (cardService.BulkUpdateStatus(ids, 0))
            {
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 禁用卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult ProhibitCardByIds(List<int> ids)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (ids.Count == 0)
            {
                rData.status = -1;
                rData.message = "没有要启动的短信卡";
                return ReturnResult(rData);
            }

            if (cardService.BulkUpdateStatus(ids, 1))
            {
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 短信任务管理
        [AllowAnonymous]
        public ActionResult TaskList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult SmsTaskList(ReqSmsTaskCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<SmsTaskDto> page = taskService.GetPages(pageIndex, pageSize, model);
            return ReturnResult(page);
        }

        public ActionResult TaskEdit()
        {
            SmsTask info = new SmsTask();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = taskService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存任务
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveTask(ReqTask reqModel)
        {
            var res = new ResultData<string>();
            SmsTask info = null;

            if (reqModel.TaskID > 0)
            {
                info = taskService.Single(reqModel.TaskID);
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
            }
            else
            {
                info = new SmsTask();
                info.CreatedTime = DateTime.Now;
                info.CreatedUserID = CurrentUser.UserId;
                info.IsDeleted = 0;
                info.Status = 1;
            }

            info.TaskName = reqModel.txtTaskName;
            info.StartDate = reqModel.txtStartDate;
            info.CarBrand = reqModel.txtCarBrand;
            info.CarSerial = reqModel.txtCarSerial;
            info.EndDate = reqModel.txtEndDate.AddHours(23).AddMinutes(59).AddSeconds(59);
            try
            {
                if (info.TaskID <= 0)
                {
                    taskService.Insert(info);
                }
                else
                {
                    taskService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelTask(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            SmsTask info = taskService.Single(id);
            if (info != null)
            {
                info.IsDeleted = 1;
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
                taskService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 任务执行周期
        public ActionResult TaskTimeList()
        {
            ViewBag.TaskId = GetParam("id");
            ViewBag.TaskName = "";
            SmsTask obj = taskService.Single(ViewBag.TaskId);
            if (obj!=null)
            {
                ViewBag.TaskName = obj.TaskName;
            }
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public ContentResult TaskTimeSearchList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            int taskId = EConvert.ToInt(GetParam("taskid"));
            Page<SmsTaskTimeDto> page = timeService.GetPages(pageIndex, pageSize, taskId);
            return ReturnResult(page);
        }

        public ActionResult TaskTimeEdit()
        {
            ViewBag.TaskId = GetParam("taskid");
            SmsTaskTime info = new SmsTaskTime();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = timeService.Single(id);
                if (info!=null)
                {
                    ViewBag.TaskId = info.TaskID;
                }
            }
            return View(info);
        }

        /// <summary>
        /// 保存任务周期
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveTaskTime(ReqTaskTime reqModel)
        {
            var res = new ResultData<string>();
            SmsTaskTime info = null;

            if (reqModel.ID > 0)
            {
                info = timeService.Single(reqModel.ID);
            }
            else
            {
                info = new SmsTaskTime();
            }

            info.TimeType = reqModel.TimeType;
            info.StartTime = reqModel.StartTime;
            info.EndTime = reqModel.EndTime;
            info.SendCount = reqModel.SendCount;
            info.TaskID = reqModel.TaskID;
            info.SendContent = reqModel.SendContent;
            try
            {
                if (info.ID <= 0)
                {
                    timeService.Insert(info);
                }
                else
                {
                    timeService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelTaskTime(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            SmsTaskTime info = timeService.Single(id);
            if (info != null)
            {
                timeService.Delete(id);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 短信发送黑名单日期
        public ActionResult BlackDay()
        {
            ViewBag.TaskId = GetParam("id");
            ViewBag.TaskName = "";
            SmsTask obj = taskService.Single(ViewBag.TaskId);
            if (obj != null)
            {
                ViewBag.TaskName = obj.TaskName;
            }
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public ContentResult BlackDaySearchList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            int taskId = EConvert.ToInt(GetParam("taskid"));
            Page<SmsBlackDayDto> page = ldayService.GetPages(pageIndex, pageSize, taskId);
            return ReturnResult(page);
        }

        public ActionResult BlackDayEdit()
        {
            ViewBag.TaskId = GetParam("taskid");
            SmsBlackDay info = new SmsBlackDay();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = ldayService.Single(id);
                if (info != null)
                {
                    ViewBag.TaskId = info.TaskID;
                }
            }
            return View(info);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveBlackDay(ReqBlackDay reqModel)
        {
            var res = new ResultData<string>();
            SmsBlackDay info = null;

            if (reqModel.DayID > 0)
            {
                info = ldayService.Single(reqModel.DayID);
            }
            else
            {
                info = new SmsBlackDay();
            }

            info.DateType = reqModel.DateType;
            info.DateValue = EConvert.ToInt(reqModel.DateValue.Replace("-",""));
            info.TaskID = reqModel.TaskID;
            try
            {
                if (info.DayID <= 0)
                {
                    ldayService.Insert(info);
                }
                else
                {
                    ldayService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelBlackDay(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            SmsBlackDay info = ldayService.Single(id);
            if (info != null)
            {
                ldayService.Delete(id);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 短信消息模板
        [AllowAnonymous]
        public ActionResult TemplateList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult SearchTemplateList(ReqSmsContentCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<SmsTemplate> page = templateService.GetPages(pageIndex, pageSize, model);
            return ReturnResult(page);
        }

        public ActionResult TemplateEdit()
        {
            SmsTemplate info = new SmsTemplate();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = templateService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveTemplate(ReqTemplate reqModel)
        {
            var res = new ResultData<string>();
            SmsTemplate info = null;
            if (reqModel.TemplateID > 0)
            {
                info = templateService.Single(reqModel.TemplateID);
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
            }
            else
            {
                info = new SmsTemplate();
                info.CreatedTime = DateTime.Now;
                info.CreatedUserID = CurrentUser.UserId;
                info.IsDeleted = 0;
            }

            info.CarBrad = reqModel.txtCarBrand;
            info.CarSerial = reqModel.txtCarSerial;
            info.SmsContent = reqModel.txtSmsContent;
            try
            {
                if (info.TemplateID <= 0)
                {
                    templateService.Insert(info);
                }
                else
                {
                    templateService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelTemplate(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            SmsTemplate info = templateService.Single(id);
            if (info != null)
            {
                info.IsDeleted = 1;
                info.UpdatedTime = DateTime.Now;
                info.UpdatedUserID = CurrentUser.UserId;
                templateService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 周期统计
        [AllowAnonymous]
        public ActionResult TaskTimeStatsticsList()
        {
            ViewBag.TaskTimeId = GetParam("id");
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult SearchTaskTimeStatsticsList(int tid)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<SmsTaskTimeStatstics> page = statsticService.GetPages(pageIndex, pageSize, tid);
            return ReturnResult(page);
        }
        #endregion




        #region 数据统计
        [AllowAnonymous]
        public ActionResult StatisticsDaySend(string startTime, string endTime)
        {
            var dtStart = DateTime.Now;
            if (string.IsNullOrEmpty(startTime))
            {
                startTime = dtStart.ToString("yyyy-MM-dd") + " 00:00:00";
            }
            else
            {
                startTime += " 00:00:00";
            }
            if (string.IsNullOrEmpty(endTime))
            {
                endTime = dtStart.ToString("yyyy-MM-dd") + " 23:59:59";
            }
            else
            {
                endTime += " 23:59:59";
            }
            ViewBag.StartTime = startTime.Replace(" 00:00:00","").Replace(" 23:59:59", "");
            ViewBag.EndTime = endTime.Replace(" 00:00:00", "").Replace(" 23:59:59", "");

            var list = svMessagePool.GetStatisticsDaySend(startTime, endTime);



            return View(list);
        }

        [AllowAnonymous]
        public ActionResult StatisticsDaySendAll(string startTime, string endTime)
        {
            var dtStart = new DateTime(2019,10,09);
            var dtEnd = DateTime.Now;
            if (string.IsNullOrEmpty(startTime))
            {
                startTime = dtStart.ToString("yyyy-MM-dd") + " 00:00:00";
            }
            else
            {
                startTime += " 00:00:00";
            }
            if (string.IsNullOrEmpty(endTime))
            {
                endTime = dtEnd.ToString("yyyy-MM-dd") + " 23:59:59";
            }
            else
            {
                endTime += " 23:59:59";
            }
            ViewBag.StartTime = startTime.Replace(" 00:00:00", "").Replace(" 23:59:59", "");
            ViewBag.EndTime = endTime.Replace(" 00:00:00", "").Replace(" 23:59:59", "");

            var list = svMessagePool.GetStatisticsDaySendAll(startTime, endTime);



            return View(list);
        }
        [AllowAnonymous]
        public ActionResult StatisticsRemain()
        {
           
            var list = svMessagePool.GetStatisticsRemain();



            return View(list);
        }
        [AllowAnonymous]
        public ActionResult StatisticsAllRemain()
        {

            var list = svMessagePool.GetStatisticsAllRemain();



            return View(list);
        }
        #endregion
    }

}

